<template>
  <div class="card">
    <div class="top">
      <a-input :allowClear="true" v-model="formData.search.phone" class="selectStyle" placeholder="用户手机"></a-input>
      <a-input
        :allowClear="true"
        v-model="formData.search.realname"
        class="selectStyle"
        placeholder="用户姓名"
      ></a-input>
      <a-select :allowClear="true" v-model="formData.search.platform" class="selectStyle" placeholder="系统类型">
        <a-select-option v-for="item in systemType" :key="item.id" :value="item.id"> {{ item.name }} </a-select-option>
      </a-select>
      <a-input
        :allowClear="true"
        v-model="formData.search.version"
        class="selectStyle"
        placeholder="版本编号"
      ></a-input>
      <a-range-picker
        v-model="formData.search.date"
        :allowClear="true"
        style="margin-right: 10px"
        :show-time="{ format: 'HH:mm' }"
        format="YYYY-MM-DD HH:mm"
        :placeholder="['注册开始时间', '注册结束时间']"
        @change="onChange"
      />
    </div>
    <div class="center">
      <a-select :allowClear="true" v-model="formData.search.is_real_verify" class="selectStyle" placeholder="实名状态">
        <a-select-option
          v-for="item in [
            { id: 1, name: '已实名' },
            { id: 0, name: '未实名' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.search.is_bind_credit" class="selectStyle" placeholder="是否绑卡">
        <a-select-option
          v-for="item in [
            { id: 1, name: '已绑卡' },
            { id: 0, name: '未绑卡' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.search.trade_status" class="selectStyle" placeholder="交易状态">
        <a-select-option
          v-for="item in [
            { id: 1, name: '已使用' },
            { id: 0, name: '未使用' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.search.type" class="selectStyle" placeholder="用户类型">
        <a-select-option
          v-for="item in [
            { id: '1', name: '中介' },
            { id: '2', name: '托管' },
            { id: '3', name: '普通' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.search.status" class="selectStyle" placeholder="账号状态">
        <a-select-option
          v-for="item in [
            { id: 1, name: '启用' },
            { id: 0, name: '禁用' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.search.bank_id" class="selectStyle" placeholder="银行名称">
        <a-select-option v-for="item in bankList" :key="item.id" :value="item.id"> {{ item.name }} </a-select-option>
      </a-select>
    </div>
    <div class="bottom">
      <a-select :allowClear="true" v-model="formData.search.level_id" class="selectStyle" placeholder="用户等级">
        <a-select-option v-for="item in userGrade" :key="item.id" :value="item.id"> {{ item.name }} </a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.search.relation" class="selectStyle" placeholder="直推间推">
        <a-select-option
          v-for="item in [
            { id: 1, name: '直推' },
            { id: 2, name: '间推' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select
        :allowClear="true"
        v-model="formData.order_by"
        :maxTagCount="1"
        mode="multiple"
        @change="handleChange"
        class="selectStyle"
        placeholder="排序方式"
      >
        <a-select-option v-for="item in sortList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-select :allowClear="true" v-model="formData.order" class="selectStyle" placeholder="排序">
        <a-select-option
          v-for="item in [
            { id: 'asc', name: '倒序' },
            { id: 'desc', name: '正序' }
          ]"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-button type="primary" style="margin-right: 10px" @click="showAdd()">新增</a-button>
      <a-button type="primary" style="margin-right: 10px" @click="sendMessage()">短信群发</a-button>
      <a-button type="primary" style="margin-right: 10px" @click="editJuri()">批量修改权限</a-button>
      <a-button type="primary" style="margin-right: 10px" @click="query">查询</a-button>
      <a-button style="margin-right: 10px" @click="reset">重置</a-button>
      <a-button type="primary">导出</a-button>
    </div>
    <a-spin :spinning="loading">
      <a-table
        :rowKey="(record, index) => index"
        x="true"
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :row-selection="rowSelection"
      >
        <template #pagination="{ total }">
          <div class="custom-pagination">总条数: {{ total }}</div>
        </template>
        <span slot="realname" slot-scope="text, record">
          <span :style="`color: ${record.status == 0 ? 'red' : ''}`" @click="viewCard(record.id)">{{
            record.realname ? record.realname : '***'
          }}</span>
        </span>
        <span slot="phone" slot-scope="text, record">
          <span class="rateStyle" @click="pushDetial(record)">{{ record.phone }}</span>
        </span>
        <span slot="is_real_verify" slot-scope="text, record">
          <span
            @click="real(record.is_real_verify, record.id)"
            :style="`color:${record.is_real_verify == 1 ? '#008000' : '#ff0000'}`"
          >
            {{ record.is_real_verify == 1 ? '已实名' : '未实名' }}
          </span>
        </span>
        <span slot="level_id" slot-scope="text, record">
          <span v-if="record.gradeBoo" @click="record.gradeBoo = false" class="rateStyle">{{
            findGrade(record.level_id)
          }}</span>
          <a-select
            size="small"
            @blur="changeGrade(record.id, record.level_id)"
            v-if="!record.gradeBoo"
            v-model="record.level_id"
            style="width: 80px"
          >
            <a-select-option v-for="item in userGrade" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </span>
        <span slot="rate" slot-scope="text, record">
          <span class="rateStyle" @click="showRate(record.id)">费率</span>
        </span>
        <span slot="view" slot-scope="text, record">
          <span class="rateStyle" @click="ViewGrade(record.id)">查看上下级</span>
        </span>
        <span slot="user_type" slot-scope="text, record">
          <span class="rateStyle" v-if="record.intermediary_uid != 0">中介</span>
          <span class="rateStyle" v-if="record.trusteeship_uid != 0">托管</span>
          <span v-if="record.intermediary_uid == 0 && record.trusteeship_uid == 0">普通</span>
        </span>
        <span slot="trade_status" slot-scope="text, record">
          <span class="rateStyle" @click="showSearch(record.id)">查询</span>
          <span style="margin: 0 3px">|</span>
          <span :style="`color:${record.trade_timestamp > 1 ? '#008000' : '#ff0000'}`">{{
            record.trade_timestamp > 0 ? '使用中' : '未使用'
          }}</span>
        </span>
        <span slot="type" slot-scope="text, record">
          <span>{{ record.type }}</span>
        </span>
        <span slot="note" slot-scope="text, record" @click="showNote(record.id)">
          <div v-if="record.is_send_sms_text == '发送中'" class="rateStyle">
            <div>{{ record.is_send_sms_text }}{{ `(${record.is_send_sms_time})` }}</div>
          </div>
          <div v-else class="rateStyle">
            {{ record.is_send_sms_text }}
          </div>
        </span>
        <span slot="app" slot-scope="text, record">
          <div>
            {{
              `${(splitStr(record.app_version) && splitStr(record.app_version)[0]) || ''}${
                splitStr(record.app_version) ? '(' : ''
              }${(splitStr(record.app_version) && splitStr(record.app_version)[1]) || ''}${
                splitStr(record.app_version) ? ')' : ''
              }`
            }}
          </div>
        </span>
        <span slot="version" slot-scope="text, record">
          <div>{{ splitStr(record.app_version) && splitStr(record.app_version)[2] }}</div>
        </span>
        <div slot="operate" slot-scope="text, record">
          <a-dropdown>
            <a class="ant-dropdown-link" @click="e => e.preventDefault()"> 更多操作 <a-icon type="down" /> </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <span @click="showClient"> 代管客户 </span>
              </a-menu-item>
              <a-menu-item>
                <span @click="passwordManagement(record.id)"> 密码管理 </span>
              </a-menu-item>
              <a-menu-item>
                <span @click="showDetail(record.id)"> 用户详情 </span>
              </a-menu-item>
              <a-menu-item>
                <span @click="editPhone(record.id, record.phone)"> 修改手机号 </span>
              </a-menu-item>
              <a-menu-item>
                <span @click="unfreeze(record.id)"> 解除快捷限制 </span>
              </a-menu-item>
              <a-menu-item>
                <span @click="joinBonus(record.id)"> 参加大盘分红 </span>
              </a-menu-item>
              <a-menu-item>
                <span @click="closeAccount(record.id)"> 账号注销 </span>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
      </a-table>
    </a-spin>
    <div class="paging">
      <a-pagination
        @change="changepage"
        @showSizeChange="showSizeChange"
        size="small"
        :total="total"
        :page-size="formData.page_size"
        :pageSizeOptions="['10', '20', '30', '40', '50']"
        :show-total="total => `共 ${total} 条`"
        show-size-changer
        show-quick-jumper
      />
    </div>
    <AddUser :isShowAdd.sync="isShowAdd" @upload="getUserList" />
    <EditJuri :isShowJuri.sync="isShowJuri" :ids.sync="ids" @upload="getUserList" />
    <SendMessage :isShowSendMessage.sync="isShowSendMessage" :ids.sync="ids" :relation_id.sync="relation_id" />
    <ProxiesClient :isShowClient.sync="isShowClient" />
    <ViewGrade :isShowView.sync="isShowView" :viewId.sync="viewId" />
    <IdCard :isShowCard.sync="isShouCard" :viewId.sync="viewId" />
    <ShowReal :isShowReal.sync="isShowReal" :viewId.sync="viewId" @upload="getUserList" />
    <Search :isShowSearch.sync="isShowSearch" :viewId.sync="viewId" />
    <UserDetail :isShowDetail.sync="isShowDetail" :viewId.sync="viewId" @upload="getUserList" />
    <EditPhone
      :isShowEditPhone.sync="isShowEditPhone"
      :viewPhone.sync="viewPhone"
      :viewId.sync="viewId"
      @upload="getUserList"
    />
    <ViewRate :isShowRate.sync="isShowRate" :viewId.sync="viewId" />
  </div>
</template>

<script>
import ViewRate from './dialog/ViewRate' //费率
import ViewGrade from './dialog/ViewGrade' // 查看上下级
import ProxiesClient from './dialog/ProxiesClient' // 代管客户
import AddUser from './dialog/AddUser' // 新增用户
import EditJuri from './dialog/EditJuri' // 批量权限
import SendMessage from './dialog/SengMessage' // 群发短信
import IdCard from './dialog/IdCard' // 查看身份证照片
import ShowReal from './dialog/ShowReal' // 实名认证
import Search from './dialog/Search.vue' // 交易状态详情
import UserDetail from './dialog/UserDetail' // 用户详情
import EditPhone from './dialog/EditPhone' // 修改手机号
import {
  getUserGradeListAPI,
  getBankListAPI,
  getSortListAPI,
  getUserListAPI,
  joinBonusAPI,
  unfreezeAPI,
  closeAccountAPI,
  resetPasswordAPI,
  changeGradeAPI,
  unRealAPI
} from '@/api/userinfo.js'
export default {
  name: 'UserList',
  components: {
    ViewRate,
    AddUser,
    EditJuri,
    SendMessage,
    ProxiesClient,
    ViewGrade,
    IdCard,
    ShowReal,
    Search,
    UserDetail,
    EditPhone
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.select_rows = selectedRows
        }
      }
    }
  },
  data() {
    return {
      viewPhone: '',
      viewId: undefined,
      ids: [],
      relation_id: undefined,
      isShowClient: false,
      isShowAdd: false,
      isShowJuri: false,
      isShowSendMessage: false,
      isShowView: false,
      isShouCard: false,
      isShowReal: false,
      isShowSearch: false,
      isShowDetail: false,
      isShowEditPhone: false,
      isShowRate: false,
      loading: false,
      total: null,
      selectedRowKeys: [],
      select_rows: [],
      formData: {
        order: undefined, // 排序
        order_by: undefined, // 排序方式
        page: 1,
        page_size: 50,
        search: {
          date: [],
          brand_id: process.env.VUE_APP_BRAND_ID,
          ctime: [], // 时间
          bank_id: undefined, // 银行名称
          is_bind_credit: undefined, // 是否绑卡
          is_real_verify: undefined, // 实名状态
          level_id: undefined, // 用户等级
          phone: '', //用户手机
          platform: undefined, //系统类型
          realname: '', // 用户姓名
          relation: undefined, // 直推间推
          status: undefined, // 账号状态
          trade_status: undefined, // 交易状态
          type: undefined, // 用户类型
          version: '' // 版本编号
        }
      },
      sortList: [],
      userGrade: [],
      bankList: [],
      systemType: [
        { id: 'android', name: 'Android' },
        { id: 'ios', name: 'ios' },
        { id: 'android|h5', name: 'Android(h5)' },
        { id: 'ios|h5', name: 'ios(h5)' },
        { id: 'other', name: '其他' }
      ],
      columns: [
        {
          title: '#',
          dataIndex: 'id',
          align: 'center',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '注册日期',
          dataIndex: 'ctime',
          align: 'center'
        },
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'realname',
          scopedSlots: { customRender: 'realname' }
        },
        {
          title: '手机号码',
          align: 'center',
          dataIndex: 'phone',
          scopedSlots: { customRender: 'phone' }
        },
        {
          title: '关系',
          dataIndex: 'relation'
        },
        {
          title: '实名',
          align: 'center',
          dataIndex: 'is_real_verify',
          scopedSlots: { customRender: 'is_real_verify' }
        },
        {
          title: '等级',
          align: 'center',
          dataIndex: 'level_id',
          scopedSlots: { customRender: 'level_id' }
        },
        {
          title: '绑卡',
          align: 'center',
          dataIndex: 'bind_credit_count'
        },
        {
          title: '费率',
          align: 'center',
          scopedSlots: { customRender: 'rate' }
        },
        {
          title: '查看上下及',
          align: 'center',
          scopedSlots: { customRender: 'view' }
        },
        {
          title: '用户类型',
          align: 'center',
          dataIndex: 'type',
          scopedSlots: { customRender: 'user_type' }
        },
        {
          title: '交易状态',
          align: 'center',
          dataIndex: 'trade_status',
          scopedSlots: { customRender: 'trade_status' }
        },
        {
          title: '直推',
          align: 'center',
          dataIndex: 'direct_count'
        },
        {
          title: '团队',
          align: 'center',
          dataIndex: 'lower_count'
        },
        {
          title: '今日收益',
          align: 'center',
          dataIndex: 'today_profit'
        },
        {
          title: '余额',
          align: 'center',
          dataIndex: 'money'
        },
        {
          title: '总收益',
          align: 'center',
          dataIndex: 'total_profit'
        },
        {
          title: '短信',
          align: 'center',
          scopedSlots: { customRender: 'note' }
        },
        {
          title: '系统型号',
          align: 'center',
          scopedSlots: { customRender: 'app' }
        },
        {
          title: '版本号',
          align: 'center',
          scopedSlots: { customRender: 'version' }
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'operate' }
        }
      ],
      tableData: []
    }
  },

  created() {
    this.getFollowType()
    this.getUserList()
  },

  methods: {
    pushDetial(record) {
      const pushInfo = JSON.stringify({ realname: record.realname, phone: record.phone })
      this.$router.push({ path: '/income/list', query: { data: pushInfo } })
    },
    query() {
      this.formData.page = 1
      this.getUserList()
    },
    findGrade(id) {
      return this.userGrade && this.userGrade.find(item => item.id == id).name
    },
    findSystem(content) {
      return this.systemType && this.systemType.find(item => item.id == content).name
    },
    splitStr(str) {
      return str && str.split('|')
    },
    onChange(value, date) {
      this.formData.search.ctime = date
    },
    handleChange(value) {
      this.formData.order_by = value
    },
    changepage(value) {
      this.formData.page = value
      this.getUserList()
    },
    showSizeChange(value, val) {
      this.formData.page_size = val
      this.getUserList()
    },
    async getFollowType() {
      const array = [
        getUserGradeListAPI({ brand_id: process.env.VUE_APP_BRAND_ID }),
        getBankListAPI({ brand_id: process.env.VUE_APP_BRAND_ID, search: { region: '全国' } }),
        getSortListAPI({ brand_id: process.env.VUE_APP_BRAND_ID })
      ]
      const [res, result, sort] = await Promise.all(array)
      this.userGrade = res.data
      this.bankList = result.data
      this.sortList = sort.data.order_by
    },
    reset() {
      this.formData = {
        order: undefined,
        order_by: undefined,
        page: 1,
        page_size: 20,
        search: {
          brand_id: process.env.VUE_APP_BRAND_ID,
          ctime: [],
          bank_id: undefined,
          is_bind_credit: undefined,
          is_real_verify: undefined,
          level_id: undefined,
          phone: '',
          platform: undefined,
          realname: '',
          relation: undefined,
          status: undefined,
          trade_status: undefined,
          type: undefined,
          version: ''
        }
      }
      this.getUserList()
    },
    async changeGrade(id, level_id) {
      const send = {
        brand_id: process.env.VUE_APP_BRAND_ID,
        ids: id,
        level_id
      }
      try {
        await changeGradeAPI(send)
        this.getUserList()
        this.$message.success('操作成功')
      } catch (error) {
        this.$message.success(error.data.msg)
      }
    },
    async getUserList() {
      try {
        this.loading = true
        this.selectedRowKeys = []
        this.select_rows = []
        const result = await getUserListAPI(this.formData)
        this.total = result.data.total
        this.tableData = result.data.list.map(item => {
          item.gradeBoo = true
          return item
        })
      } finally {
        this.selectedRowKeys = []
        this.select_rows = []
        this.loading = false
      }
    },
    showAdd() {
      this.isShowAdd = true
    },
    sendMessage() {
      if (this.select_rows && this.select_rows.length == 0) return this.$message.error('至少选择一个用户')
      this.ids = this.select_rows.map(item => item.id)
      console.log(this.ids)
      this.isShowSendMessage = true
    },
    showNote(id) {
      this.relation_id = id
      this.isShowSendMessage = true
    },
    editJuri() {
      if (this.select_rows && this.select_rows.length == 0) return this.$message.error('至少选择一个用户')
      this.ids = this.select_rows.map(item => item.id)
      this.isShowJuri = true
    },
    showClient() {
      this.isShowClient = true
    },
    ViewGrade(id) {
      this.viewId = id
      this.isShowView = true
    },
    joinBonus(id) {
      this.$confirm({
        title: '大盘分红',
        content: h => <div>确定参加大盘分红吗？</div>,
        icon: h => <span></span>,
        onOk: async () => {
          try {
            await joinBonusAPI({ brand_id: process.env.VUE_APP_BRAND_ID, uid: id })
            this.getUserList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel() {
          return
        },
        class: 'test'
      })
    },
    passwordManagement(id) {
      this.$confirm({
        title: '确定要操作密码吗？',
        content: h => <div style="color:red">请谨慎操作！</div>,
        icon: h => <span></span>,
        cancelText: '恢复',
        okText: '重置',
        onOk: async () => {
          try {
            await resetPasswordAPI({ brand_id: process.env.VUE_APP_BRAND_ID, type: 1, user_id: id })
            this.getUserList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel: async () => {
          try {
            await resetPasswordAPI({ brand_id: process.env.VUE_APP_BRAND_ID, type: 2, user_id: id })
            this.getUserList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        class: 'test'
      })
    },
    unfreeze(id) {
      this.$confirm({
        title: '确定要操作解除快捷限制吗？',
        content: h => <div style="color:red">请谨慎操作！</div>,
        icon: h => <span></span>,
        cancelText: '恢复',
        okText: '解除',
        onOk: async () => {
          try {
            await unfreezeAPI({ brand_id: process.env.VUE_APP_BRAND_ID, type: 2, user_id: id })
            this.getUserList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel: async () => {
          try {
            await unfreezeAPI({ brand_id: process.env.VUE_APP_BRAND_ID, type: 1, user_id: id })
            this.getUserList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        class: 'test'
      })
    },
    closeAccount(id) {
      this.$confirm({
        title: '确定注销此账号吗？',
        content: h => <div style="color:red">请谨慎操作！</div>,
        icon: h => <span></span>,
        onOk: async () => {
          try {
            await closeAccountAPI({ brand_id: process.env.VUE_APP_BRAND_ID, user_id: id })
            this.getUserList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel() {
          return
        },
        class: 'test'
      })
    },
    viewCard(id) {
      this.viewId = id
      this.isShouCard = true
    },
    real(boo, id) {
      if (boo == 0) {
        this.viewId = id
        this.isShowReal = true
      } else {
        this.$confirm({
          title: '确定取消实名认证？',
          onOk: async () => {
            try {
              await unRealAPI({
                brand_id: process.env.VUE_APP_BRAND_ID,
                id_card: '',
                is_real_verify: '0',
                realname: '',
                user_id: id
              })
              this.getUserList()
              this.$message.success('操作成功')
            } catch (error) {
              this.$message.error(error.data.msg)
            }
          },
          onCancel() {
            return
          },
          class: 'test'
        })
      }
    },
    showSearch(id) {
      this.viewId = id
      this.isShowSearch = true
    },
    showDetail(id) {
      this.viewId = id
      this.isShowDetail = true
    },
    editPhone(id, phone) {
      this.viewPhone = phone
      this.viewId = id
      this.isShowEditPhone = true
    },
    showRate(id) {
      this.viewId = id
      this.isShowRate = true
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-select-selection__rendered {
  white-space: nowrap;
  ul {
    height: 0;
    display: flex;
  }
}
/deep/ .ant-table-body {
  white-space: nowrap;
  width: 100%;
  overflow-x: auto;
  font-size: 15px;
}

/* 整个滚动条 */
/deep/ .ant-table-body::-webkit-scrollbar {
  width: 5px;
  height: 6px;
}

/deep/ .ant-table-body::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #1890ff;
}

/deep/ .ant-table-body::-webkit-scrollbar-track {
  border-radius: 1px;
  background: #f1f1f1;
}
.card {
  padding: 10px;
  background-color: #fff;
  .top {
    display: flex;
  }
  .center {
    display: flex;
    margin: 10px 0;
  }
  .bottom {
    margin-bottom: 10px;
    display: flex;
  }
}
.selectStyle {
  width: 160px;
  margin-right: 10px;
}
.rateStyle {
  cursor: pointer;
  color: #1890ff;
}
.paging {
  display: flex;
  flex-direction: row-reverse;
  padding: 10px;
}
</style>
